#version 120
 
uniform float lightVector;
uniform sampler2D texture0;
uniform sampler2D texture1;

float sphereHeight( float x, float y ) {
    float c = x*x + y*y - 1.0;
		
    float disc = -4.0 * c;
    if( disc < 0.0 )
        return 0.0;

    float distSqrt = sqrt( disc );
    float q = distSqrt / 2.0;

    float t0 = q;
    float t1 = c / q;

    if( t0 > t1 ) {
        float temp = t0;
        t0 = t1;
        t1 = temp;
    }

    if( t1 < 0.0 )
        return 0.0;

    if( t0 < 0.0 )
        return t1;
    else
        return t0;
}

void main(void) {
    float rad = radians( lightVector );
    vec3 ln = normalize( vec3( cos( rad ), sin( rad ), 0.0 ) );

    float x = (gl_TexCoord[0].x - 0.5) * 2.0;
    float y = (gl_TexCoord[0].y - 0.5) * 2.0;
    float z = sphereHeight( x, y );

    vec3 n = normalize( vec3( x, y, z ) );

    vec4 bump = texture2D( texture1, vec2( gl_TexCoord[0] ) );
    bump -= vec4( 0.5, 0.5, 0.5, 0.0 );

    vec4 diffuse;
    vec4 specular;
    if( z > 0.0 ) {
        diffuse = vec4( 1.0, 1.0, 1.0, 1.0 ) * max( dot( n, ln ), 0.0 );

        //vec3 h = normalize( ln + vec3( 0.0, 0.0, 1.0 ) );
	//float s = pow( max( 0.0, dot( n, h ) ), 255.0 );
	//specular = vec4( s, s, s, 1.0 );

        vec3 r = normalize( reflect( ln, n ) );
        vec4 specColor = vec4( 1.0, 1.0, 1.0, 1.0 );
        vec3 eye = vec3( 0.0, 0.0, -1.0 );
	specular = specColor * pow( max( dot( r, eye ), 0.0), 50.0 ) * 0.8;	
    } else {
        diffuse = vec4( 0.0, 0.0, 0.0, 0.0 );
        specular = vec4( 0.0, 0.0, 0.0, 0.0 );
    }

    gl_FragColor = texture2D( texture0, vec2( gl_TexCoord[0] ) );
    gl_FragColor *= diffuse;
    gl_FragColor += specular;
}